package com.appsindy.common.interceptor;

import com.appsindy.common.AppsindyConstants;
import com.appsindy.common.action.UserAware;
import com.appsindy.common.bo.GlobalUser;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.interceptor.SessionAware;

/**
 * @author Lee
 */
public class AuthenticationInterceptor implements Interceptor {
    
    public final static String version = "$Rev: 785 $";
    
    public AuthenticationInterceptor() {}
    
    public void destroy() {}
    
    public void init() {}
    
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        Action action = (Action)actionInvocation.getAction();
        if(action instanceof SessionAware){
            return actionInvocation.invoke();
        }
        Map session = actionInvocation.getInvocationContext().getSession();

        GlobalUser user = (GlobalUser)session.get(AppsindyConstants.S_USER_LOGIN);
        if(user == null) {
            System.out.println("[AuthenticationInterceptor.intercept] Session timeout, then forward to \"" + Action.LOGIN + "\" page !");
            return Action.LOGIN;
            
        } else {
            HttpServletRequest request = (HttpServletRequest)actionInvocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
            //String menuId = request.getParameter("menuId");
            
            if(action instanceof UserAware) {
//                    Map params = actionInvocation.getInvocationContext().getParameters();
//              	  Iterator paramIt = params.keySet().iterator();
                ((UserAware)action).setGlobalUser(user);
            }
            return actionInvocation.invoke();
        }
    }
    
//    private String getCurrentUri(HttpServletRequest request) {
//        String uri = request.getRequestURI();
//        String queryString = request.getQueryString();
//        if(queryString != null && !queryString.equals(""))
//            uri += "?" + queryString;
//        return uri;
//    }
    
}
